package com.mall.live.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.common.response.CommonResponse;
import com.mall.constant.enums.CommonStatus;
import com.mall.constant.strings.SuccessMsg;
import com.mall.entity.TbCar;
import com.mall.entity.TbUser;
import com.mall.entity.bargain.BgOrder;
import com.mall.entity.live.TbLiveProduct;
import com.mall.live.fegin.OrderFegin;
import com.mall.live.mapper.LiveProductMapper;
import com.mall.live.service.LiveProductService;
import com.mall.live.vo.Details;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Component
@Transactional
public class LiveProductServiceImpl implements LiveProductService {

    @Autowired
    private LiveProductMapper liveProductMapper;
    @Autowired
    private OrderFegin orderFegin;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取所有在直播的商品
     * 按照时间倒序
     * @return CommonResponse
     */
    @Override
    public CommonResponse findAll() {
        List<TbLiveProduct> liveProducts = liveProductMapper.findAll();
        return new CommonResponse(CommonStatus.SUCCESS.getCode(), SuccessMsg.SUCCESS_CODE_200,liveProducts);
    }

    /**
     * 获取直播标题包含‘搭配’的商品
     * 按照时间倒序
     * @return CommonResponse
     */
    @Override
    public CommonResponse findRecommendList() {
        List<TbLiveProduct> liveProducts = liveProductMapper.findRecommendList();
        return new CommonResponse(CommonStatus.SUCCESS.getCode(), SuccessMsg.SUCCESS_CODE_200,liveProducts);
    }

    @Override
    public PageInfo findLiveProduct(Long itemId, Integer page, Integer size) {
        PageHelper.startPage(page,size);
        List<TbLiveProduct> liveProducts = liveProductMapper.findLiveProductByItemId(itemId);
        return new PageInfo(liveProducts);
    }

    /**
     * 获取直播间售卖的商品
     * @param lid
     * @return
     */
    @Override
    public List<TbLiveProduct> liveGoods(Long lid) {
        return liveProductMapper.liveGoods(lid);
    }

    /**
     * 加入购物车
     * @param id
     * @param token
     * @param num
     */
    @Override
    public CommonResponse car(Long id,String token,Integer num) {

        //根据token获取登录人信息
        TbUser user = (TbUser) redisTemplate.opsForValue().get(token);
        //获取购买的商品
        TbLiveProduct tbLiveProduct=liveProductMapper.findOne(id);
        if(user==null){
            return new CommonResponse(-1,"请先登录");
        }else {
            //获取redis里面的购物车
            List<TbCar> cars= (List<TbCar>)redisTemplate.boundHashOps("token").get(user.getName());
            TbCar car=new TbCar();
            //判断是否有购物车
            if(cars!=null){

                //断购物车里面是否存在该商品
                car=isTbCar(cars,tbLiveProduct.getItemId());

                if(car==null){
                    TbCar tbCar = new TbCar();
                    tbCar.setStatus("1");
                    tbCar.setCreateTime(new Date());
                    tbCar.setPrice(tbLiveProduct.getPrice());
                    tbCar.setUserId(user.getId());
                    tbCar.setGoodsId(tbLiveProduct.getItemId());
                    tbCar.setTotal(new BigDecimal(tbLiveProduct.getPrice().doubleValue()*num));
                    tbCar.setBuyNum(num);
                    car=tbCar;
                    cars.add(car);
                }else {
                    //数量合并
                car.setBuyNum(car.getBuyNum() + num);
                    //小计计算
                car.setTotal(new BigDecimal(car.getPrice().doubleValue() * car.getBuyNum()));
                }
                redisTemplate.boundHashOps("token").put(user.getName(),cars);
            }else {
                car.setStatus("1");
                car.setCreateTime(new Date());
                car.setPrice(tbLiveProduct.getPrice());
                car.setUserId(user.getId());
                car.setGoodsId(tbLiveProduct.getItemId());
                car.setPrice(new BigDecimal(tbLiveProduct.getPrice().doubleValue()*num));
                car.setBuyNum(num);
                cars = new ArrayList<>();
                cars.add(car);
                redisTemplate.boundHashOps("token").put(user.getName(),cars);
            }
            return new CommonResponse(0,"加入成功");
        }
    }

    /**
     * 判断购物车里面是否有商品
     * @param cars
     * @param itemId
     * @return
     */
    private TbCar isTbCar(List<TbCar> cars, Long itemId) {
        for (TbCar car : cars) {
            if(car.getGoodsId().equals(itemId)){
                return car;
            }
        }
        return null;
    }


    /**
     * 购买，获得购物车里需要购买的信息加入订单
     * @param id
     * @return
     */
    @Override
    public CommonResponse buy(String token,Long id) {
        //根据token获取登录人信息
        TbUser user = (TbUser) redisTemplate.opsForValue().get(token);
        //获取redis里面的购物车
        List<TbCar> cars= (List<TbCar>)redisTemplate.boundHashOps("token").get(user.getName());
        TbCar tbCar=MyCar(cars,id);
        if(tbCar!=null){
            BgOrder bgOrder = new BgOrder();
            bgOrder.setCreateTime(new Date());
            bgOrder.setStatus("0");
            bgOrder.setType("1");
            bgOrder.setPrice(tbCar.getTotal());
            bgOrder.setUid(tbCar.getUserId().longValue());
            bgOrder.setItemSpecId(tbCar.getGoodsId());
            Long oid=liveProductMapper.addOrder(bgOrder);
            System.out.println(oid);
            String s = orderFegin.doPay(oid);
            cars.remove(tbCar);
            redisTemplate.boundHashOps("token").put(user.getName(),cars);
            return new CommonResponse(0,"购买成功",s);
        }else {
            return new CommonResponse(-1,"购买失败");
        }


    }

    /**
     * 购买，查看购买的商品
     * @param cars
     * @param id
     * @return
     */
    private TbCar MyCar(List<TbCar> cars, Long id) {
        for (TbCar car : cars) {
            if(car.getGoodsId().equals(id)){
                return car;
            }
        }
        return null;
    }

    /**
     * 查看我的购物车
     * @param token
     * @return
     */
    @Override
    public List<TbCar> myCar(String token) {
        //根据token获取登录人信息
        TbUser user = (TbUser) redisTemplate.opsForValue().get(token);
        //获取redis里面的购物车
        List<TbCar> cars= (List<TbCar>)redisTemplate.boundHashOps("token").get(user.getName());
        return cars;
    }

    /**
     * 商品详情
     * @param id
     * @return
     */
    @Override
    public Details details(Long id) {
        return liveProductMapper.details(id);
    }
}
